package pl.org.lutra.planner.gui.main;

import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;

import pl.org.lutra.planner.log.Log;
import pl.org.lutra.planner.model.input.InputModelListener;

public class InputTextField extends JTextField {
	private static final long serialVersionUID = -2024170106885549510L;

	public InputTextField(DocumentFilter documentFilter, InputModelListener inputModelListener) {
		final AbstractDocument document = (AbstractDocument) getDocument();

		if (documentFilter != null) {
			document.setDocumentFilter(documentFilter);
		}

		if (inputModelListener != null)
			document.addDocumentListener(new InputDocumenListener(inputModelListener));
	}

	private class InputDocumenListener implements DocumentListener {
		private InputModelListener inputModelListener;

		private InputDocumenListener(InputModelListener inputModelListener) {
			this.inputModelListener = inputModelListener;
		}

		@Override
		public void removeUpdate(DocumentEvent e) {
			update(e);
		}

		@Override
		public void insertUpdate(DocumentEvent e) {
			update(e);
		}

		@Override
		public void changedUpdate(DocumentEvent e) {
			update(e);
		}

		private void update(DocumentEvent e) {
			try {
				Document document = e.getDocument();
				inputModelListener.updateModel(document.getText(0, document.getLength()));
			} catch (BadLocationException exception) {
				Log.error("Cannot get text", exception);
			}
		}
	}

}
